"use client";

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

type PageKey = 'home' | 'login' | 'register' | 'product';

export type UIPreferencesContextType = {
  opacities: Record<PageKey, number>;
  getOpacity: (page: PageKey) => number;
  setOpacity: (page: PageKey, opacity: number) => void;
};

const UIPreferencesContext = createContext<UIPreferencesContextType | undefined>(undefined);

const DEFAULT_OPACITIES: Record<PageKey, number> = {
  home: 0.15,
  login: 0.25,
  register: 0.25,
  product: 0.15,
};

export function UIPreferencesProvider({ children }: { children: ReactNode }) {
  const [opacities, setOpacities] = useState<Record<PageKey, number>>(() => {
    try {
      const storedOpacities = localStorage.getItem('ui-opacities');
      if (storedOpacities) {
        // Merge stored settings with defaults to ensure all keys exist
        return { ...DEFAULT_OPACITIES, ...JSON.parse(storedOpacities) };
      }
    } catch (error) {
      console.error("Failed to read opacities from localStorage", error);
    }
    return DEFAULT_OPACITIES;
  });

  useEffect(() => {
    try {
      localStorage.setItem('ui-opacities', JSON.stringify(opacities));
    } catch (error) {
      console.error("Failed to save opacities to localStorage", error);
    }
  }, [opacities]);

  const setOpacity = (page: PageKey, opacity: number) => {
    setOpacities(prev => ({ ...prev, [page]: opacity }));
  };

  const getOpacity = (page: PageKey): number => {
    return opacities[page] ?? 1.0;
  };

  return (
    <UIPreferencesContext.Provider value={{ opacities, getOpacity, setOpacity }}>
      {children}
    </UIPreferencesContext.Provider>
  );
}

export function useUIPreferences() {
  const context = useContext(UIPreferencesContext);
  if (context === undefined) {
    throw new Error('useUIPreferences must be used within a UIPreferencesProvider');
  }
  return context;
} 